﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Indigox.CMS.Administration
{
    public class WriteLock
    {
        private bool locked = false;
        private Mutex mutex = new Mutex();

        public IDisposable Lock()
        {
            return new LockEntry( this );
        }

        public void Wait( Callback callback )
        {
            if ( this.locked )
            {
                Mutex.WaitAll( new WaitHandle[] { this.mutex } );
            }
            callback.Invoke();
        }

        public delegate void Callback();

        private class LockEntry : IDisposable
        {
            private WriteLock writeLock;

            public LockEntry( WriteLock writeLock )
            {
                this.writeLock = writeLock;
                this.writeLock.mutex.WaitOne();
                this.writeLock.locked = true;
            }

            public void Dispose()
            {
                this.writeLock.locked = false;
                this.writeLock.mutex.ReleaseMutex();
            }
        }
    }
}
